package com.cooba.welcome;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.*;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.activitys.MainTabActivity;
import com.cooba.application.MyApplication;
import com.cooba.bean.BannerBean;
import com.cooba.bean.MacBean;
import com.cooba.broadCastReceiver.MyReceiver;
import com.cooba.dialog.ComfirmDialog;
import com.cooba.utils.BannerUtils;
import com.cooba.utils.CarURL;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2015/12/29.
 * 欢迎页面
 */
public class AppStartActivity extends AppCompatActivity {

    private FrameLayout ads_local_fl;
    private ImageView ads_local_container_iv;
    private FrameLayout ads_net_container_fl;
    private TextView ads_count_time;

    private HttpUtils httpUtils;
    private RequestParams params;
    private MyReceiver myReceiver;
    private Boolean isIncar;
    private String mac;
    private BannerBean banner;
    private SplashAD splashAD;
    public boolean canJump = false;
    private Timer timer1;
    private int timecount = 5;
    private JSONObject json;
    private String neturl;
    private String factoryName;
    private MacBean macbean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String isFirstOpen = SharedPreferencesUtil.getData(AppStartActivity.this,Constants.IS_FIRST_START,"0");//0 第一次启动 1 已启动
        // 如果是第一次启动，则先进入功能引导页
        if (isFirstOpen.equals("0")) {
            Intent intent = new Intent(this, WelcomeActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        setContentView(R.layout.activity_app_start);
        initView();
        requestData();
    }


    private void requestData() {
        httpUtils = new HttpUtils();
        httpUtils.configDefaultHttpCacheExpiry(0);
        httpUtils.configCurrentHttpCacheExpiry(0);
        httpUtils.configTimeout(5000);
        httpUtils.configSoTimeout(5000);
        httpUtils.send(HttpRequest.HttpMethod.GET, "http://a.cooba.cc/macmark.json", null, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "车载数据获取失败");
                getBanner();

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "车载数据获取成功" + responseInfo.result);
//                    json = new JSONObject(responseInfo.result);
//                    String mac = json.get("MAC").toString();
                try {
                    macbean=new Gson().fromJson(responseInfo.result, MacBean.class);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                MyApplication application = MyApplication.getMyApplication();
                application.setIsInCar(true);
                application.setMac(macbean.getMAC());
                application.setFactoryName(macbean.getFactory());
                getNet();

            }
        });
    }

    private void getNet() {
        initIncar();
        httpUtils = new HttpUtils();
        httpUtils.configTimeout(5000);
        httpUtils.configSoTimeout(5000);
        params=new RequestParams();
        if (isIncar) {
            if (factoryName.equals("TBS")) {
                neturl = CarURL.carneturl_new;
            }else {
                neturl=CarURL.carneturl_old;
               params.addBodyParameter("action","user_auth");
            }
            httpUtils.send(HttpRequest.HttpMethod.POST, neturl,params, new RequestCallBack<String>() {
                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    Log.e("wei", "获取通网失败");
                   getBanner();
                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Log.e("wei", "获取成功通网成功" + responseInfo.result);
                    getBanner();
                }
            });
        }
    }


    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
        factoryName=application.getFactoryName();
    }

    private void getBanner() {
        initIncar();
        String urlbanner;
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String now_time = sDateFormat.format(new java.util.Date());
        httpUtils = new HttpUtils();
        params = new RequestParams();
        httpUtils.configTimeout(5000);
        httpUtils.configSoTimeout(5000);
        params.addBodyParameter("now_time", now_time);
        params.addBodyParameter("tag", "loadpage");
        if (isIncar) {
            params.addBodyParameter("mac", mac);
            urlbanner = CarURL.bannerList;
        } else {
            urlbanner = ServerURL.httpUrl + ServerURL.bannerList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlbanner, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取本地广告失败");
                initNetAD();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "取本地广告成功" + responseInfo.result);
                try {
                    banner = new Gson().fromJson(responseInfo.result, BannerBean.class);
                    if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                        initLocalAD();
                    } else {
                        initNetAD();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initNetAD() {
        splashAD = new SplashAD(this, ads_net_container_fl, Constants.APPID, Constants.AppStart_Banner, new SplashADListener() {
            @Override
            public void onADDismissed() {
                Log.i("AD_DEMO", "SplashADDismissed");
                next();
            }

            @Override
            public void onNoAD(int i) {
                Log.i("AD_DEMO", "LoadSplashADFail, eCode=" + i);
                /** 如果加载广告失败，则直接跳转 */
                startActivity(new Intent(AppStartActivity.this, MainTabActivity.class));
                finish();
            }

            @Override
            public void onADPresent() {
                Log.i("AD_DEMO", "SplashADPresent");
            }

            @Override
            public void onADClicked() {
                Log.i("AD_DEMO", "SplashADClicked");
            }
        });
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            this.startActivity(new Intent(this, MainTabActivity.class));
            this.finish();
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    /**
     * 开屏页最好禁止用户对返回按钮的控制
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void initView() {
        ads_net_container_fl = (FrameLayout) findViewById(R.id.ads_net_container_fl);
        ads_local_container_iv = (ImageView) findViewById(R.id.ads_local_container_iv);
        ads_local_fl = (FrameLayout) findViewById(R.id.ads_local_fl);
        ads_count_time = (TextView) findViewById(R.id.ads_count_time);
        ads_count_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timer1.cancel();
                startActivity(new Intent(AppStartActivity.this, MainTabActivity.class));
                finish();
            }
        });
    }


    private void initLocalAD() {
        BitmapUtils bitmapUtils = new BitmapUtils(AppStartActivity.this);
        bitmapUtils.display(ads_local_container_iv, banner.getBannerList().get(0).getHome_pic());
        BannerUtils.getBannerStatistic(banner.getBannerList().get(0), "1", AppStartActivity.this);
        ads_local_container_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BannerUtils.getBannerStatistic(banner.getBannerList().get(0), "0", AppStartActivity.this);
            }
        });
        timer1 = new Timer();
        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {        // UI thread
                    @Override
                    public void run() {
                        ads_count_time.setText(timecount + " | 跳过");
                        timecount--;
                        if (timecount <= 0) {
                            timer1.cancel();
                            startActivity(new Intent(AppStartActivity.this, MainTabActivity.class));
                            finish();
                        }
                    }
                });

            }
        }, 0, 1000);
        ads_local_fl.setVisibility(View.VISIBLE);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
